import { Request, Response } from "express";
import { query } from "../config/database";
import { KnowledgeCategory } from "../model/types";
import {
  successResponse,
  errorResponse,
  paginatedResponse,
} from "../utils/response";

export class KnowledgeController {
  // 获取知识分类列表
  static async getCategories(req: Request, res: Response): Promise<void> {
    try {
      const {
        page = 1,
        pageSize = 20,
        name,
        isActive,
        sortBy = "sortOrder",
        sortOrder = "asc",
      } = req.query;

      const offset = (Number(page) - 1) * Number(pageSize);
      let whereConditions = [];
      let params: any[] = [];

      // 构建WHERE条件
      if (name) {
        whereConditions.push("name LIKE ?");
        params.push(`%${name}%`);
      }

      if (isActive !== undefined) {
        whereConditions.push("is_active = ?");
        params.push(isActive === "true" ? 1 : 0);
      }

      const whereClause =
        whereConditions.length > 0
          ? `WHERE ${whereConditions.join(" AND ")}`
          : "";

      // 获取总数
      const countQuery = `SELECT COUNT(*) as total FROM knowledge_categories ${whereClause}`;
      const { rows: countRows } = await query(countQuery, params);
      const total = countRows[0].total;
      const totalPages = Math.ceil(total / Number(pageSize));

      // 获取分类列表
      const categoryQuery = `
        SELECT
          kc.id,
          kc.name,
          kc.description,
          kc.icon,
          kc.sort_order as sortOrder,
          kc.is_active as isActive,
          kc.created_at as createdAt,
          COUNT(ka.id) as articleCount
        FROM knowledge_categories kc
        LEFT JOIN knowledge_articles ka ON kc.id = ka.category_id AND ka.is_published = 1
        ${whereClause}
        GROUP BY kc.id
        ORDER BY kc.${sortBy} ${sortOrder}
        LIMIT ? OFFSET ?
      `;

      params.push(Number(pageSize), offset);
      const { rows } = await query(categoryQuery, params);

      paginatedResponse(res, rows, {
        page: Number(page),
        pageSize: Number(pageSize),
        total,
        totalPages,
      });
    } catch (error) {
      console.error("获取知识分类列表失败:", error);
      errorResponse(res, "获取知识分类列表失败");
    }
  }

  // 根据ID获取知识分类
  static async getCategoryById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      const { rows } = await query(
        `
        SELECT
          kc.id,
          kc.name,
          kc.description,
          kc.icon,
          kc.sort_order as sortOrder,
          kc.is_active as isActive,
          kc.created_at as createdAt,
          COUNT(ka.id) as articleCount
        FROM knowledge_categories kc
        LEFT JOIN knowledge_articles ka ON kc.id = ka.category_id AND ka.is_published = 1
        WHERE kc.id = ?
        GROUP BY kc.id
      `,
        [id]
      );

      if (rows.length === 0) {
        return errorResponse(res, "知识分类不存在", 404);
      }

      successResponse(res, rows[0]);
    } catch (error) {
      console.error("获取知识分类详情失败:", error);
      errorResponse(res, "获取知识分类详情失败");
    }
  }

  // 创建知识分类
  static async createCategory(req: Request, res: Response): Promise<void> {
    try {
      const {
        name,
        description,
        icon,
        sortOrder = 0,
        isActive = true,
      } = req.body;

      // 验证必填字段
      if (!name) {
        return errorResponse(res, "分类名称不能为空");
      }

      // 检查分类名是否已存在
      const { rows: existingCategories } = await query(
        "SELECT id FROM knowledge_categories WHERE name = ?",
        [name]
      );

      if (existingCategories.length > 0) {
        return errorResponse(res, "分类名称已存在");
      }

      // 创建分类
      const insertQuery = `
        INSERT INTO knowledge_categories (name, description, icon, sort_order, is_active)
        VALUES (?, ?, ?, ?, ?)
      `;

      const { rows } = await query(insertQuery, [
        name,
        description || null,
        icon || null,
        sortOrder,
        isActive,
      ]);

      successResponse(res, { id: rows[0].insertId }, "知识分类创建成功", 201);
    } catch (error) {
      console.error("创建知识分类失败:", error);
      errorResponse(res, "创建知识分类失败");
    }
  }

  // 更新知识分类
  static async updateCategory(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const { name, description, icon, sortOrder, isActive } = req.body;

      // 检查分类是否存在
      const { rows: existingCategories } = await query(
        "SELECT id FROM knowledge_categories WHERE id = ?",
        [id]
      );

      if (existingCategories.length === 0) {
        return errorResponse(res, "知识分类不存在", 404);
      }

      // 检查分类名是否已被其他分类使用
      if (name) {
        const { rows: nameCheck } = await query(
          "SELECT id FROM knowledge_categories WHERE name = ? AND id != ?",
          [name, id]
        );

        if (nameCheck.length > 0) {
          return errorResponse(res, "分类名称已存在");
        }
      }

      // 更新分类
      const updateFields = [];
      const params = [];

      if (name !== undefined) {
        updateFields.push("name = ?");
        params.push(name);
      }

      if (description !== undefined) {
        updateFields.push("description = ?");
        params.push(description);
      }

      if (icon !== undefined) {
        updateFields.push("icon = ?");
        params.push(icon);
      }

      if (sortOrder !== undefined) {
        updateFields.push("sort_order = ?");
        params.push(sortOrder);
      }

      if (isActive !== undefined) {
        updateFields.push("is_active = ?");
        params.push(isActive);
      }

      if (updateFields.length > 0) {
        const updateQuery = `UPDATE knowledge_categories SET ${updateFields.join(
          ", "
        )} WHERE id = ?`;
        params.push(id);
        await query(updateQuery, params);
      }

      successResponse(res, null, "知识分类更新成功");
    } catch (error) {
      console.error("更新知识分类失败:", error);
      errorResponse(res, "更新知识分类失败");
    }
  }

  // 删除知识分类
  static async deleteCategory(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      // 检查分类是否存在
      const { rows: existingCategories } = await query(
        "SELECT id FROM knowledge_categories WHERE id = ?",
        [id]
      );

      if (existingCategories.length === 0) {
        return errorResponse(res, "知识分类不存在", 404);
      }

      // 检查分类下是否有文章
      const { rows: articles } = await query(
        "SELECT COUNT(*) as count FROM knowledge_articles WHERE category_id = ?",
        [id]
      );

      if (articles[0].count > 0) {
        return errorResponse(res, "该分类下还有文章，无法删除");
      }

      // 删除分类
      await query("DELETE FROM knowledge_categories WHERE id = ?", [id]);

      successResponse(res, null, "知识分类删除成功");
    } catch (error) {
      console.error("删除知识分类失败:", error);
      errorResponse(res, "删除知识分类失败");
    }
  }

  // 切换分类状态
  static async toggleCategoryStatus(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      const { id } = req.params;

      // 检查分类是否存在
      const { rows: existingCategories } = await query(
        "SELECT id, is_active FROM knowledge_categories WHERE id = ?",
        [id]
      );

      if (existingCategories.length === 0) {
        return errorResponse(res, "知识分类不存在", 404);
      }

      const currentStatus = existingCategories[0].is_active;
      const newStatus = currentStatus ? 0 : 1;

      await query(
        "UPDATE knowledge_categories SET is_active = ? WHERE id = ?",
        [newStatus, id]
      );

      successResponse(res, null, "分类状态更新成功");
    } catch (error) {
      console.error("更新分类状态失败:", error);
      errorResponse(res, "更新分类状态失败");
    }
  }

  // 更新分类排序
  static async updateCategorySort(req: Request, res: Response): Promise<void> {
    try {
      const { categories } = req.body; // [{ id: 1, sortOrder: 1 }, { id: 2, sortOrder: 2 }, ...]

      if (!Array.isArray(categories)) {
        return errorResponse(res, "参数格式不正确");
      }

      // 批量更新排序
      for (const category of categories) {
        await query(
          "UPDATE knowledge_categories SET sort_order = ? WHERE id = ?",
          [category.sortOrder, category.id]
        );
      }

      successResponse(res, null, "分类排序更新成功");
    } catch (error) {
      console.error("更新分类排序失败:", error);
      errorResponse(res, "更新分类排序失败");
    }
  }
}
